/**
 * 
 */
package com.ofek.eventos.net.lks;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import com.ofek.utils.DebugBlock;

/**
 * @author Ofek
 *
 */

@DebugBlock
public class LastKnownHandler<ID> implements Serializable,Iterable<Entry<ID,Long>>,Cloneable {
	private final HashMap<ID,Long> hashMap;
	/**
	 * 
	 */
	public LastKnownHandler() {
		hashMap = new HashMap<ID, Long>();
	}
	private LastKnownHandler(final HashMap<ID,Long> hashMap) {
		this.hashMap = hashMap;
	}
	public void updateIfNeeded(final ID uid, final long version) {
		final Long lastKnown = hashMap.get(uid);
		if (lastKnown==null || lastKnown<version) 
			hashMap.put(uid,version);
	}

	public boolean isKnown(final ID id, final long t) {
		final Long lastKnown = hashMap.get(id);
		if (lastKnown==null || lastKnown<t) 
			return false;
		return true;

	}
	public void forget(final ID id) {
		hashMap.remove(id);
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(final Object obj) {
		if (super.equals(obj)) return true;
		if (obj instanceof LastKnownHandler) 
			return ((LastKnownHandler) obj).hashMap.equals(hashMap);
		return false;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return hashMap.toString();
	}
	public void reset() {
		hashMap.clear();
	}
	/* (non-Javadoc)
	 * @see java.lang.Iterable#iterator()
	 */
	@Override
	public Iterator<Entry<ID, Long>> iterator() {
		return hashMap.entrySet().iterator();
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#clone()
	 */
	@Override
	public Object clone() {
		final LastKnownHandler<ID> lastKnownHandler = new LastKnownHandler<>((HashMap<ID, Long>) hashMap.clone());
		return lastKnownHandler;
	}
	public LastKnownHandler<ID> merge(final LastKnownHandler<ID> lkh){
		hashMap.putAll(lkh.hashMap);
		return this;
	}
}
